<?php

namespace app\admin\controller;

use app\admin\library\Excel;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use think\facade\Db;
use think\db\exception\PDOException;
use think\exception\ValidateException;

/**
 * 保单信息
 *
 */
class XInsurance extends Backend
{
    /**
     * XInsurance模型对象
     * @var \app\admin\model\XInsurance
     */
    protected $model = null;
    protected $pot= null;
    protected $quickSearchField = ['POLICYNO'];
    protected $noNeedLogin      = ['*'];

    protected $defaultSortField = 'POLICYNO,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XInsurance;
//        $this->pot =new x_insurancepot
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
       //1按箱号2按保单
        $crop=$this->request->get('CORP');
        $wheres=[];
        if($crop){
            $wheres['CORP']=$crop;
        }
        $sy_type=$this->request->get('code');
        $sy_where='';
        if($sy_type && $sy_type=='GXBX'){
            $sy_where="valid='1' and datediff(day,getdate(),enddate)<(select isnull(max(CAST(attr as int)),0) from codelib where code='GXBX' and codetype='alarmsetup')";
        }
        $type=$this->request->get('type')?:'1';
        if($type==1){
            if($sy_where!=''){
                $res = $this->model
                    ->withJoin($this->withJoinTable, $this->withJoinType)
                    ->with('claims')
                    ->where($where)
                    ->where($sy_where)
                    ->where($wheres)
                    ->order($order)
//                ->fetchSql()->select();
                    ->paginate($limit);
            }else{
                $array=['x_insurance.TCNO'];
                $two_where=[];
                foreach ($where as $k=>$item) {
                    if(in_array($item[0],$array)){
                        $two_where[]=['p.'.substr( $item[0],strripos( $item[0],".")+1),$item[1],$item[2]];
                        unset($where[$k]);
                    }
                }
                $res = $this->model
                    ->field('x.POLICYNO,x.POLICY,x.STARTDATE,x.ENDDATE,x.NOTE,x.MONEY,x.SUNINSURED,TCNO')
                    ->alias('x')
                    ->join('x_insurancepot p','x.POLICYNO=p.POLICYNO')
                    ->withJoin($this->withJoinTable, $this->withJoinType)
                    ->with('claims')
                    ->where($where)
                    ->where($two_where)
                    ->where($wheres)
                    ->order($order)
//                ->fetchSql()->select();
                    ->paginate($limit);
                foreach ($res as $re) {
                    foreach($re['claims'] as $k=>$v){
                        if($re['TCNO']!=$v['TCNO']){
                            unset($re['claims'][$k]);
                        }
                    }
                }
            }

        }else{
            $res = $this->model
                ->field("x.POLICYNO,x.POLICY,x.STARTDATE,x.ENDDATE,x.NOTE,x.MONEY,x.SUNINSURED")
                ->alias('x')
//                ->join('x_insurancepot p','x.POLICYNO=p.POLICYNO')
                ->withJoin($this->withJoinTable, $this->withJoinType)
                ->with('pot')
                ->where($where)
                ->where($sy_where)
                ->where($wheres)
//                ->group('x.POLICYNO')
//                ->order($order)
//                ->fetchSql()->select();
                ->paginate($limit);
//        var_dump($res);die;
        }


        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * 箱号导入
     */
    public function importData()
    {
        $files = $this->request->file("file");

        // 调用类库，读取excel中的内容
        $data = Excel::importExcel($files);
        $add=[];
        $adminInfo          = $this->auth->getInfo();

        foreach ($data as $k=>$datum) {
            $id=Db::table('X_INSURANCEPOT')->where('POLICYNO',$datum[0])->value('POLICYNO');
            $tcno=Db::table('x_pot')->where('TCNO',$datum[1])->value('TCNO');
            if(!$tcno){
                $this->error($datum[1].'箱号不存在不存在 ');
            }
            if($id==''){
                $this->error($datum[0].'保单不存在，请先输入保单 ');
            }
            if($datum[1]==''){
                $this->error("导入文件的第 $k 行，箱号不存在，导入失败");
            }
            $add[$k]['POLICYNO']=$datum[0];
            $add[$k]['TCNO']=$datum[1];
            $add[$k]['UPLOADFLAG']='1';
            $add[$k]['OP']=$adminInfo['nickname'];
            $add[$k]['OPTIME']=date('Y-m-d H:i:s',time());
        }
        $result = false;


            $result=Db::table('X_INSURANCEPOT')->insertAll($add);

        if ($result !== false) {
            $this->success(__('Added successfully'));
        } else {
            $this->error(__('No rows were added'));
        }

    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
}